<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6"><el-button type="primary" @click="addDialogVisible =true">添加</el-button></el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" style="width: 100%" :border="true" :stripe="true">
        <el-table-column type="index" label="序号" width="100"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChang(scope.row)"></el-switch>
        </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配权限 -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
            </el-tooltip>
            {{scope.row.id}}
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDiaologClosed">
        <!-- 内容主体区域 -->
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑用户" :visible.sync="editDialogVisible">
        <!-- 内容主体区域 -->
        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" @close="editDiaologClosed">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" :disabled="!!editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo('editFormRef')">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    let checkEmail=(rule, value, callback)=>{
      const regEmail=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if(regEmail.test(value)) {
        return callback()
      }
      return callback(new Error('请输入正确的邮箱'))
    }
    // 验证手机号的规则
    let checkMobile=(rule, value, callback)=>{
      const regMobile =/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      if(regMobile.test(value)) {
        return callback()
      }
      return callback(new Error('请输入合法的手机号'))
    } 
    return {
      //获取用户列表查询参数
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 当前每页显示多少条
        pagesize: 10,
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible:false,
      // 添加用户的表单数据
      addForm:{
        username:'admin2',
        password:'123456',
        email:'admin2@qq.com',
        mobile:'15166601870'
      },
      editForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      // 添加用户表单的验证规则
      addFormRules:{
        username:[
          {required: true, message:'请输入用户名', trigger: 'blur'},
          {min: 3, max:10, message:'用户名的长度在3——10之间', trigger: 'blur'},
        ],
        password:[
          {required: true, message:'请输入密码', trigger: 'blur'},
          {min: 6, max:15, message:'用户名的长度在3——10之间', trigger: 'blur'},
        ],
        email:[
          {required: true, message:'请输入邮箱', trigger: 'blur'},
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          {required: true, message:'请输入邮箱', trigger: 'blur'},
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules:{
        username:[
          {required: true, message:'请输入用户名', trigger: 'blur'},
          {min: 3, max:10, message:'用户名的长度在3——10之间', trigger: 'blur'},
        ],
        password:[
          {required: true, message:'请输入密码', trigger: 'blur'},
          {min: 6, max:15, message:'用户名的长度在3——10之间', trigger: 'blur'},
        ],
        email:[
          {required: true, message:'请输入邮箱', trigger: 'blur'},
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          {required: true, message:'请输入邮箱', trigger: 'blur'},
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //
      editDialogVisible:false

    }
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(this.userlist)
    },
    // 监听pagesize改变的事件
    handleSizeChange(newsize){
      this.queryInfo.pagesize=newsize
      this.getUsersList()
      console.log(this.queryInfo.pagesize)
    },
    // 
    handleCurrentChange(newpage){
      this.queryInfo.pagenum=newpage
      this.getUsersList()
    },
    async userStateChang(userInfo){
      const {data:res}= await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status!==200){
        userInfo.mg_state= !userInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 点击按钮添加新用户
    addUser(){
      this.$refs.addFormRef.validate(async valid=>{
        if (!valid)  return
        //验证通过，发起添加用户的网络请求
        const {data:res}= await this.$http.post('users',this.addForm)
        if(res.meta.status !==201) this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addDialogVisible=false
        this.getUsersList()
      })
    },
    editUserInfo(){
      this.$refs.editFormRef.validate(async valid=>{
        if(!valid) return false
        const {data:res}= await this.$http.put(`users/${this.editForm.id}`,{email:this.editForm.email, mobile: this.editForm.mobile})
        if(res.meta.status!==200){
          return this.$message.error('修改用户信息失败')
        }
        // 关闭对话框
        this.editDialogVisible=false
        // 刷新数据列表
        this.getUsersList()
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })

    },
    async removeUserById(id){
      //弹窗，提示是否删除
      const confirmResult=await this.$confirm('是否继续删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消删除，则返回值为字符串cancel
      if(confirmResult !=='confirm'){
        return this.$message.info('已取消删除')
      }
      const {data:res}=await this.$http.delete(`users/${id}`)
      if(res.meta.status !== 200){
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUsersList()
    },
    //监听添加用户对话框关闭事件
    addDiaologClosed(){
      this.$refs.addFormRef.resetFields()
    },
    editDiaologClosed(){
      this.$refs.addFormRef.resetFields()
    },
    // 展示编辑对话框
    async showEditDialog(id){
      const {data:res}= await this.$http.get(`users/${id}`)
      if(res.meta.status !==200){
        return this.$message.error('查询用户信息失败')
      }
      this.editForm =res.data
      this.editDialogVisible =true
    }
  },
  created() {
    this.getUsersList()
  },
}
</script>
<style lang="scss" scoped>
</style>